﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace ZL.OAuthClientTest
{
    class Program
    {
        static void Main(string[] args)
        {

           // const string url = "http://localhost:14094/";
           // var _httpClient = new HttpClient();
           // _httpClient.BaseAddress = new Uri(url);
           // var parameters = new Dictionary<string, string>();
           // parameters.Add("client_id", "zhanglei");
           // parameters.Add("client_secret", "123");
           // parameters.Add("grant_type", "client_credentials");

           // var responseValue = _httpClient.PostAsync("/oauth/token", new FormUrlEncodedContent(parameters))
           //     .Result.Content.ReadAsStringAsync().Result;


           // Console.WriteLine(responseValue);
           // var parameters1 = new Dictionary<string, string>();
           // parameters1.Add("Bearer", responseValue);
           // var token= JObject.Parse(responseValue)["access_token"].Value<string>();
           //// _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
           //// Console.WriteLine(_httpClient.GetAsync("/api/values/Get").Result);
           // var data = _httpClient.PostAsync("/api/values", new FormUrlEncodedContent(parameters1))
           //    .Result.Content.ReadAsStringAsync().Result;
           // Console.WriteLine(data);
            
            new OAuthClientTest().Call_WebAPI_By_Access_Token();

            Console.ReadKey();
        }
    }


    public class OAuthClientTest
    {
        private HttpClient _httpClient;

        public OAuthClientTest()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://localhost:14094");
        }

       
        public async Task Call_WebAPI_By_Access_Token()
        {
            var token = await GetAccessToken();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            Console.WriteLine(await (await _httpClient.GetAsync("/api/values")).Content.ReadAsStringAsync());
        }

        private async Task<string> GetAccessToken()
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("client_id", "zhanglei");
            parameters.Add("client_secret", "123");
            parameters.Add("grant_type", "client_credentials");

            var response = await _httpClient.PostAsync("/oauth/token", new FormUrlEncodedContent(parameters));
            var responseValue = await response.Content.ReadAsStringAsync();

            return JObject.Parse(responseValue)["access_token"].Value<string>();
        }
    }

}
